<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TechHub - Digital Electronics Store</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Arial', sans-serif;
        }

        body {
            background-color: #f8f9fa;
        }

        /* Header Styles */
        .header {
            background-color: #fff;
            padding: 1rem;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            position: fixed;
            width: 100%;
            top: 0;
            z-index: 1000;
        }

        .nav {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1200px;
            margin: 0 auto;
        }

        .logo {
            font-size: 24px;
            font-weight: bold;
            color: #2196F3;
        }

        .search-bar {
            flex: 1;
            max-width: 600px;
            margin: 0 20px;
            display: flex;
        }

        .search-bar input {
            width: 100%;
            padding: 10px;
            border: 2px solid #2196F3;
            border-radius: 4px 0 0 4px;
            outline: none;
        }

        .search-bar button {
            padding: 10px 20px;
            background: #2196F3;
            border: none;
            color: white;
            border-radius: 0 4px 4px 0;
            cursor: pointer;
        }

        .nav-links {
            display: flex;
            gap: 20px;
            align-items: center;
        }

        .nav-links a {
            text-decoration: none;
            color: #333;
            font-weight: 500;
        }

        .cart-icon {
            position: relative;
            cursor: pointer;
        }

        .cart-count {
            position: absolute;
            top: -8px;
            right: -8px;
            background-color: #2196F3;
            color: white;
            border-radius: 50%;
            padding: 2px 6px;
            font-size: 12px;
        }

        /* Main Content */
        .main-content {
            max-width: 1200px;
            margin: 80px auto 20px;
            padding: 20px;
        }

        /* Categories */
        .categories {
            background: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            gap: 20px;
            overflow-x: auto;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        .category-item {
            text-align: center;
            cursor: pointer;
            padding: 15px;
            border-radius: 8px;
            transition: all 0.3s;
            min-width: 120px;
        }

        .category-item:hover {
            background-color: #f0f7ff;
            transform: translateY(-2px);
        }

        .category-item i {
            font-size: 28px;
            color: #2196F3;
            margin-bottom: 8px;
        }

        /* Products Grid */
        .products-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 25px;
            margin-bottom: 40px;
        }

        .product-card {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            transition: transform 0.3s;
        }

        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
        }

        .product-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
        }

        .product-info {
            padding: 20px;
        }

        .product-title {
            font-size: 16px;
            margin-bottom: 12px;
            color: #333;
            height: 48px;
            overflow: hidden;
            line-height: 1.4;
        }

        .product-price {
            color: #2196F3;
            font-weight: bold;
            font-size: 20px;
            margin-bottom: 12px;
        }

        .product-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 13px;
            color: #666;
            margin-bottom: 15px;
        }

        .add-to-cart {
            background-color: #2196F3;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            width: 100%;
            transition: background-color 0.3s;
            font-weight: 500;
        }

        .add-to-cart:hover {
            background-color: #1976D2;
        }

        /* Shopping Cart */
        .cart-modal {
            display: none;
            position: fixed;
            top: 0;
            right: 0;
            width: 400px;
            height: 100vh;
            background: white;
            box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
            padding: 20px;
            z-index: 1001;
        }

        .cart-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .close-cart {
            cursor: pointer;
            font-size: 24px;
        }

        .cart-items {
            max-height: calc(100vh - 200px);
            overflow-y: auto;
        }

        .cart-item {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .cart-item-image {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 4px;
        }

        .cart-item-info {
            flex: 1;
        }

        .cart-total {
            position: absolute;
            bottom: 20px;
            left: 20px;
            right: 20px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .search-bar {
                display: none;
            }

            .cart-modal {
                width: 100%;
            }

            .products-grid {
                grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
            }
        }

        .pagination {
            display: flex;
            justify-content: center;
            gap: 8px;
            margin-bottom: 20px;
            align-items: center;
        }

        .pagination button,
        .pagination span {
            background: #fff;
            border: 1px solid #2196F3;
            color: #2196F3;
            padding: 6px 14px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background 0.2s, color 0.2s;
            min-width: 36px;
        }

        .pagination button.active {
            background: #2196F3;
            color: #fff;
            cursor: default;
        }

        .pagination button:disabled {
            color: #ccc;
            border-color: #eee;
            background: #f8f8f8;
            cursor: not-allowed;
        }

        .pagination span.ellipsis {
            border: none;
            background: none;
            color: #aaa;
            cursor: default;
            padding: 0 6px;
            font-size: 18px;
        }

        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }

            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
    </style>
</head>

<body>
    <!-- Header -->
    <header class="header">
        <nav class="nav">
            <div class="logo">TechHub</div>
            <div class="search-bar">
                <input type="text" placeholder="搜索商品、手机、笔记本电脑..." onkeypress="handleSearchKeyPress(event)">
                <button onclick="searchProducts()"><i class="fas fa-search"></i></button>
            </div>
            <div class="nav-links">
                <a href="profile.html"><i class="fas fa-user"></i> 我的账户</a>
                <a href="profile.html#orders" onclick="goToOrders()"><i class="fas fa-shopping-bag"></i> 我的订单</a>
                <div class="cart-icon" onclick="toggleCart()">
                    <i class="fas fa-shopping-cart"></i>
                    <span class="cart-count">0</span>
                </div>
            </div>
        </nav>
    </header>

    <!-- Main Content -->
    <main class="main-content">
        <!-- Categories -->
        <div class="categories" id="categoriesBar"></div>
        <!-- Products Section -->
        <section id="products">
            <div class="products-grid" id="productsGrid">
                <!-- Products will be rendered by JS -->
            </div>
            <div class="pagination" id="pagination"></div>
        </section>
    </main>

    <!-- Shopping Cart Modal -->
    <div class="cart-modal" id="cartModal">
        <div class="cart-header">
            <h2>购物车</h2>
            <span class="close-cart" onclick="toggleCart()">&times;</span>
        </div>
        <div class="cart-items" id="cartItems">
            <!-- Cart items will be added here dynamically -->
        </div>
        <div class="cart-total">
            <h3>总计: ¥<span id="cartTotal">0.00</span></h3>
            <button class="add-to-cart" onclick="checkout()">结算</button>
        </div>
    </div>

    <script>
        // 商品数据
        let products = [];
        const pageSize = 8;
        let currentPage = 1;
        let totalPages = 1;
        let categories = [];
        let currentCategoryId = null;

        // 动态加载分类导航
        async function loadCategories() {
            try {
                const response = await fetch('/categories');
                categories = await response.json();

                const bar = document.getElementById('categoriesBar');
                bar.innerHTML = '';

                // 全部商品按钮
                const allBtn = document.createElement('div');
                allBtn.className = 'category-item';
                allBtn.innerHTML = `<i class="fas fa-th-large"></i><div>全部商品</div>`;
                allBtn.onclick = () => {
                    currentCategoryId = null;
                    currentPage = 1;
                    fetchProducts(1);
                    // 激活全部商品
                    setActiveCategory(null);
                };
                bar.appendChild(allBtn);

                // 分类按钮
                categories.forEach(cat => {
                    const btn = document.createElement('div');
                    btn.className = 'category-item';
                    btn.innerHTML = `<i class="fas fa-tag"></i><div>${cat.name}</div>`;
                    btn.onclick = () => {
                        currentCategoryId = cat.id;
                        currentPage = 1;
                        fetchProducts(1, cat.id);
                        setActiveCategory(cat.id);
                    };
                    bar.appendChild(btn);
                });
                // 默认激活全部商品
                setActiveCategory(null);
            } catch (e) {
                console.error('加载分类失败', e);
            }
        }

        // 设置激活样式
        function setActiveCategory(catId) {
            document.querySelectorAll('.category-item').forEach((item, idx) => {
                item.classList.remove('active');
                if ((catId === null && idx === 0) || (categories[idx - 1] && categories[idx - 1].id === catId)) {
                    item.classList.add('active');
                }
            });
        }

        // 支持商品按照分类的分页查询
        async function fetchProducts(page, categoryId = null) {
            try {
                let url = `/pageProduct?pageNum=${page}&pageSize=${pageSize}`;
                if (categoryId)//检查分类id是否存在
                    url += `&categoryId=${categoryId}`;
                const response = await fetch(url);
                const data = await response.json();
                products = data.list;
                totalPages = data.pages;
                renderProducts(page);
                renderPagination();
            } catch (error) {
                console.error('Error fetching products:', error);
            }
        }

        //将商品数据渲染到页面
        function renderProducts(page) {
            const grid = document.getElementById('productsGrid');
            grid.innerHTML = '';
            //遍历商品数据
            products.forEach(product => {
                //将商品渲染为HTML
                grid.innerHTML += `
                <div class="product-card" onclick="viewProductDetail(${product.id})" style="cursor: pointer;">
                    <img src="${product.imageUrl || 'https://images.pexels.com/photos/788946/pexels-photo-788946.jpeg?auto=compress&w=500'}" 
                         alt="${product.name}" 
                         class="product-image"
                         onerror="this.src=''">
                    <div class="product-info">
                        <h3 class="product-title">${product.name}</h3>
                        <p class="product-price">¥${product.price.toFixed(2)}</p>
                        <div class="product-meta">
                            <span id="product-stock-${product.id}">库存: ${product.stock}</span>
                        </div>
                        <button class="add-to-cart" onclick="addToCart(${product.id}, '${product.name.replace(/'/g, "\'")}', ${product.price}, this); event.stopPropagation();">加入购物车</button>
                    </div>
                </div>
                `;
            });
        }

        // 分页逻辑
        function renderPagination() {
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';
            // 上一页按钮
            pagination.innerHTML += `<button onclick="goToPage(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''}>&laquo;</button>`;
            // 页码逻辑
            let pageArr = [];
            if (totalPages <= 7) {
                for (let i = 1; i <= totalPages; i++) pageArr.push(i);
            } else {
                if (currentPage <= 4) {
                    pageArr = [1, 2, 3, 4, 5, '...', totalPages];
                } else if (currentPage >= totalPages - 3) {
                    pageArr = [1, '...', totalPages - 4, totalPages - 3, totalPages - 2, totalPages - 1, totalPages];
                } else {
                    pageArr = [1, '...', currentPage - 1, currentPage, currentPage + 1, '...', totalPages];
                }
            }
            pageArr.forEach(p => {
                if (p === '...') {
                    pagination.innerHTML += `<span class="ellipsis">...</span>`;
                } else {
                    pagination.innerHTML += `<button class="${p === currentPage ? 'active' : ''}" onclick="goToPage(${p})">${p}</button>`;
                }
            });
            // 下一页按钮
            pagination.innerHTML += `<button onclick="goToPage(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''}>&raquo;</button>`;
        }

        function goToPage(page) {
            currentPage = page;
             (page, currentCategoryId);
        }

        // 初始化
        loadCategories();
        fetchProducts(currentPage);

        // 购物车功能
        let cart = [];
        let cartTotal = 0;

        function toggleCart() {
            const cartModal = document.getElementById('cartModal');
            cartModal.style.display = cartModal.style.display === 'block' ? 'none' : 'block';
        }

        // 页面加载时获取购物车数据
        async function loadCartData() {
            try {
                const response = await fetch('/getCartList');
                if (response.ok) {
                    const cartItems = await response.json();
                    //请求getCartList接口成功后 先清空本地购物车
                    cart = [];
                    cartTotal = 0;
                    //遍历购物车数据
                    for (const cartItem of cartItems) {
                        try {
                            const productResponse = await fetch(`/getById?id=${cartItem.productId}`);
                            if (productResponse.ok) {
                                const product = await productResponse.json();
                                if (product) {
                                    // 检查cart数组中是否已存在该商品
                                    let existing = cart.find(item => item.id === product.id);
                                    if (existing) {
                                        // 合并数量
                                        existing.quantity += cartItem.quantity;
                                    } else {
                                        cart.push({
                                            id: product.id,
                                            name: product.name,
                                            price: product.price,
                                            quantity: cartItem.quantity
                                        });
                                    }
                                    cartTotal += product.price * cartItem.quantity;
                                }
                            }
                        } catch (error) {
                            console.error('获取商品详情失败:', error);
                        }
                    }
                    document.querySelector('.cart-count').textContent = cart.reduce((sum, item) => sum + item.quantity, 0);
                    updateCartDisplay();
                }
            } catch (error) {
                console.log('获取购物车数据失败，可能是未登录:', error);
            }
        }

        //添加到购物车
        async function addToCart(id, name, price, button) {
            try {
                // 检查本地购物车是否已有该商品
                const existingItem = cart.find(item => item.id === id);
                if (existingItem) {
                    // 如果已存在，询问是否增加数量
                    const newQuantity = existingItem.quantity + 1;
                    const confirmed = confirm(`该商品已在购物车中，当前数量：${existingItem.quantity}，是否增加到 ${newQuantity}？`);
                    if (!confirmed) return;

                    // 调用后端更新购物车
                    const response = await fetch('/addCart', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            productId: id,
                            quantity: 1
                        })
                    });

                    const result = await response.text();
                    console.log('更新购物车返回:', result);

                    if (result.includes('成功')) {
                        // 更新本地购物车数量
                        existingItem.quantity = newQuantity;
                        cartTotal += price;
                        document.querySelector('.cart-count').textContent = cart.reduce((sum, item) => sum + item.quantity, 0);
                        updateCartDisplay();
                        showToast(`商品数量已更新为 ${newQuantity}`, 'success');
                        refreshProductStock(id);
                    } else {
                        showToast(result || '更新失败，请重试', 'error');
                    }
                    return;
                }

                // 新商品，询问购买数量
                const quantity = prompt(`请输入购买数量（默认1）：`, '1');
                if (!quantity || isNaN(quantity) || parseInt(quantity) <= 0) {
                    showToast('请输入有效的数量', 'error');
                    return;
                }

                const buyQuantity = parseInt(quantity);

                // 调用后端接口添加购物车
                const response = await fetch('/addCart', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        productId: id,
                        quantity: buyQuantity
                    })
                });

                const result = await response.text();
                console.log('添加购物车返回:', result);

                if (result.includes('成功')) {
                    // 检查本地cart数组是否已存在该商品
                    let existing = cart.find(item => item.id === id);
                    if (existing) {
                        existing.quantity += buyQuantity;
                    } else {
                        cart.push({ id, name, price, quantity: buyQuantity });
                    }
                    cartTotal += price * buyQuantity;
                    document.querySelector('.cart-count').textContent = cart.reduce((sum, item) => sum + item.quantity, 0);
                    updateCartDisplay();

                    // 按钮状态变化
                    button.textContent = '已加入购物车';
                    button.style.backgroundColor = '#1976D2';
                    setTimeout(() => {
                        button.textContent = '加入购物车';
                        button.style.backgroundColor = '#2196F3';
                    }, 1000);

                    // 成功提示
                    showToast(`商品已成功加入购物车！数量：${buyQuantity}`, 'success');
                    refreshProductStock(id);
                } else {
                    // 失败提示
                    showToast(result || '添加失败，请重试', 'error');
                }
            } catch (error) {
                console.error('添加购物车失败:', error);
                showToast('添加失败，请检查登录状态', 'error');
            }
        }
        //购物车显示
        function updateCartDisplay() {
            const cartItems = document.getElementById('cartItems');
            const cartTotalElement = document.getElementById('cartTotal');
            cartItems.innerHTML = '';

            if (cart.length === 0) {
                cartItems.innerHTML = `
                    <div style="text-align: center; padding: 40px; color: #666;">
                        <div style="font-size: 3rem; margin-bottom: 10px;">🛒</div>
                        <p>购物车为空</p>
                    </div>
                `;
                cartTotalElement.textContent = '0.00';
                return;
            }

            cart.forEach((item, index) => {
                const itemElement = document.createElement('div');
                itemElement.className = 'cart-item';
                itemElement.innerHTML = `
                    <div class="cart-item-info">
                        <h4>${item.name}</h4>
                        <p>¥${item.price.toFixed(2)} × ${item.quantity}</p>
                        <p style="font-weight: bold; color: #2196F3;">小计: ¥${(item.price * item.quantity).toFixed(2)}</p>
                    </div>
                    <div style="display: flex; flex-direction: column; gap: 5px; align-items: center;">
                        <div style="display: flex; align-items: center; gap: 5px;">
                            <button onclick="updateQuantity(${index}, -1)" style="width: 25px; height: 25px; border: 1px solid #ddd; background: white; cursor: pointer;">-</button>
                            <span style="min-width: 30px; text-align: center;">${item.quantity}</span>
                            <button onclick="updateQuantity(${index}, 1)" style="width: 25px; height: 25px; border: 1px solid #ddd; background: white; cursor: pointer;">+</button>
                        </div>
                        <button onclick="removeFromCart(${index})" style="color: #f44336; background: none; border: none; cursor: pointer; font-size: 12px;">移除</button>
                    </div>
                `;
                cartItems.appendChild(itemElement);
            });
            cartTotalElement.textContent = cartTotal.toFixed(2);
        }
        //更新商品数量
        async function updateQuantity(index, change) {
            const item = cart[index];
            const newQuantity = item.quantity + change;

            if (newQuantity <= 0) {
                // 数量为0时删除商品
                await removeFromCart(index);
                return;
            }

            try {
                // 调用后端更新购物车
                const response = await fetch('/addCart', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        productId: item.id,
                        quantity: change > 0 ? 1 : -1 // 增加或减少1
                    })
                });

                const result = await response.text();
                console.log('更新数量返回:', result);

                if (result.includes('成功')) {
                    // 更新本地购物车
                    const oldTotal = item.price * item.quantity;
                    item.quantity = newQuantity;
                    const newTotal = item.price * item.quantity;
                    cartTotal = cartTotal - oldTotal + newTotal;

                    document.querySelector('.cart-count').textContent = cart.reduce((sum, item) => sum + item.quantity, 0);
                    updateCartDisplay();

                    showToast(`商品数量已更新为 ${newQuantity}`, 'success');
                    refreshProductStock(item.id);
                } else {
                    showToast(result || '更新失败，请重试', 'error');
                }
            } catch (error) {
                console.error('更新数量失败:', error);
                showToast('更新失败，请重试', 'error');
            }
        }
        //移除商品
        async function removeFromCart(index) {
            const item = cart[index];
            try {
                // 调用后端删除接口
                const response = await fetch(`/deleteCart?productId=${item.id}`, {
                    method: 'DELETE'
                });

                const result = await response.text();
                console.log('删除返回:', result); // 调试输出

                if (result.includes('成功')) {
                    // 从本地购物车移除
                    cartTotal -= item.price * item.quantity;
                    cart.splice(index, 1);
                    document.querySelector('.cart-count').textContent = cart.reduce((sum, item) => sum + item.quantity, 0);
                    updateCartDisplay();
                    showToast('商品已从购物车移除', 'success');
                    refreshProductStock(item.id);
                } else {
                    showToast(result || '删除失败，请重试', 'error');
                }
            } catch (error) {
                console.error('删除购物车商品失败:', error);
                showToast('删除失败，请重试', 'error');
            }
        }
        //显示该用户的购物车信息
        async function checkout() {
            if (cart.length === 0) {
                alert('您的购物车为空！');
                return;
            }
            // 调用后端添加订单接口(下单)
            try {
                const response = await fetch('/addOrder', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({}), // 后端只用ThreadLocalUtil.get()取userId
                    credentials: 'include' // 必须加
                });
                const result = await response.text();
                if (result.includes('成功')) {
                    showToast('下单成功！正在跳转到订单页面...', 'success');
                    // 结算前保存所有商品id
                    const productIds = cart.map(item => item.id);
                    // 清空本地购物车
                    cart = [];
                    cartTotal = 0;
                    document.querySelector('.cart-count').textContent = '0';
                    updateCartDisplay();
                    toggleCart();

                    // 刷新所有相关商品库存
                    productIds.forEach(id => refreshProductStock(id));

                    // 延迟跳转到订单页面
                    setTimeout(() => {
                        window.location.href = 'profile.html#orders';
                    }, 1500);
                } else {
                    showToast('下单失败：' + result, 'error');
                }
            } catch (error) {
                showToast('下单失败，请重试', 'error');
            }
        }

        // 回车键搜索
        function handleSearchKeyPress(event) {
            if (event.key === 'Enter') {
                searchProducts();
            }
        }

        // 搜索功能
        async function searchProducts() {
            const searchTerm = document.querySelector('.search-bar input').value.trim();
            if (!searchTerm) {
                // 如果搜索词为空，加载所有商品
                fetchProducts(1);
                return;
            }

            try {
                const response = await fetch(`/getByName?name=${encodeURIComponent(searchTerm)}`);
                const products = await response.json();

                if (products && products.length > 0) {
                    // 显示搜索结果
                    renderSearchResults(products);
                } else {
                    // 显示无结果
                    const grid = document.getElementById('productsGrid');
                    grid.innerHTML = `
                        <div style="grid-column: 1 / -1; text-align: center; padding: 40px;">
                            <div style="font-size: 3rem; color: #ddd; margin-bottom: 15px;">🔍</div>
                            <p style="color: #666; font-size: 16px;">未找到匹配的商品</p>
                            <button onclick="fetchProducts(1)" style="margin-top: 15px; padding: 8px 16px; background: #2196F3; color: white; border: none; border-radius: 4px; cursor: pointer;">返回全部商品</button>
                        </div>
                    `;
                    document.getElementById('pagination').innerHTML = '';
                }
            } catch (error) {
                console.error('搜索商品失败:', error);
                alert('搜索失败，请重试');
            }
        }
        // 渲染搜索结果
        function renderSearchResults(products) {
            const grid = document.getElementById('productsGrid');
            grid.innerHTML = '';
            products.forEach(product => {
                grid.innerHTML += `
                <div class="product-card" onclick="viewProductDetail(${product.id})" style="cursor: pointer;">
                    <img src="${product.imageUrl || 'https://images.pexels.com/photos/788946/pexels-photo-788946.jpeg?auto=compress&w=500'}" 
                         alt="${product.name}" 
                         class="product-image"
                         onerror="this.src=''">
                    <div class="product-info">
                        <h3 class="product-title">${product.name}</h3>
                        <p class="product-price">¥${product.price.toFixed(2)}</p>
                        <div class="product-meta">
                            <span id="product-stock-${product.id}">库存: ${product.stock}</span>
                        </div>
                        <button class="add-to-cart" onclick="addToCart(${product.id}, '${product.name.replace(/'/g, "\'")}', ${product.price}, this); event.stopPropagation();">加入购物车</button>
                    </div>
                </div>
                `;
            });
            // 隐藏分页
            document.getElementById('pagination').innerHTML = '';
        }

        // 查看商品详情
        async function viewProductDetail(productId) {
            try {
                const response = await fetch(`/getById?id=${productId}`);
                const product = await response.json();

                if (product) {
                    // 显示商品详情弹窗
                    showProductDetailModal(product);
                } else {
                    alert('商品不存在！');
                }
            } catch (error) {
                console.error('获取商品详情失败:', error);
                alert('获取商品详情失败，请重试');
            }
        }

        // 显示商品详情弹窗
        function showProductDetailModal(product) {
            // 创建详情弹窗
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                z-index: 1000;
                display: flex;
                justify-content: center;
                align-items: center;
            `;

            modal.innerHTML = `
                <div style="
                    background: white;
                    padding: 30px;
                    border-radius: 12px;
                    max-width: 600px;
                    width: 90%;
                    max-height: 80vh;
                    overflow-y: auto;
                    position: relative;
                ">
                    <button onclick="this.closest('.product-detail-modal').remove()" style="
                        position: absolute;
                        top: 15px;
                        right: 20px;
                        background: none;
                        border: none;
                        font-size: 24px;
                        cursor: pointer;
                        color: #666;
                    ">&times;</button>
                    
                    <div style="display: flex; gap: 20px; margin-bottom: 20px;">
                        <img src="${product.imageUrl || 'https://images.pexels.com/photos/788946/pexels-photo-788946.jpeg?auto=compress&w=500'}" 
                             alt="${product.name}" 
                             style="width: 200px; height: 200px; object-fit: cover; border-radius: 8px;"
                             onerror="this.src=''">
                        <div style="flex: 1;">
                            <h2 style="margin: 0 0 15px 0; color: #333;">${product.name}</h2>
                            <p style="font-size: 24px; font-weight: bold; color: #2196F3; margin: 0 0 15px 0;">¥${product.price.toFixed(2)}</p>
                            <div style="margin-bottom: 15px;">
                                <span id="product-stock-${product.id}-modal" style="color: #666;">库存: ${product.stock}</span>
                            </div>
                            <button onclick="addToCart(${product.id}, '${product.name.replace(/'/g, "\'")}', ${product.price}, this); this.closest('.product-detail-modal').remove();" 
                                    style="
                                        background: #2196F3;
                                        color: white;
                                        border: none;
                                        padding: 12px 24px;
                                        border-radius: 6px;
                                        cursor: pointer;
                                        font-size: 16px;
                                        font-weight: 500;
                                    ">
                                加入购物车
                            </button>
                        </div>
                    </div>
                    
                    ${product.description ? `
                    <div style="border-top: 1px solid #eee; padding-top: 20px;">
                        <h3 style="margin: 0 0 10px 0; color: #333;">商品描述</h3>
                        <p style="color: #666; line-height: 1.6; margin: 0;">${product.description}</p>
                    </div>
                    ` : ''}
                </div>
            `;

            modal.className = 'product-detail-modal';
            document.body.appendChild(modal);

            // 点击背景关闭弹窗
            modal.addEventListener('click', function (e) {
                if (e.target === modal) {
                    modal.remove();
                }
            });
        }

        // 显示提示信息
        function showToast(message, type = 'info') {
            const toast = document.createElement('div');
            toast.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 12px 20px;
                border-radius: 6px;
                color: white;
                font-weight: 500;
                z-index: 10000;
                animation: slideIn 0.3s ease;
            `;

            if (type === 'success') {
                toast.style.backgroundColor = '#4CAF50';
            } else if (type === 'error') {
                toast.style.backgroundColor = '#f44336';
            } else {
                toast.style.backgroundColor = '#2196F3';
            }

            toast.textContent = message;
            document.body.appendChild(toast);

            setTimeout(() => {
                toast.remove();
            }, 3000);
        }

        // 跳转到订单页面
        function goToOrders() {
            window.location.href = 'profile.html#orders';
        }

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function () {
            fetchProducts(1);
            loadCartData(); // 加载购物车数据
        });

        // 在合适位置添加刷新库存函数
        async function refreshProductStock(productId) {
            try {
                const response = await fetch(`/getById?id=${productId}`);
                if (response.ok) {
                    const product = await response.json();
                    // 主列表
                    const stockSpan = document.getElementById(`product-stock-${productId}`);
                    if (stockSpan) {
                        stockSpan.textContent = `库存: ${product.stock}`;
                    }
                    // 详情弹窗
                    const modalStockSpan = document.getElementById(`product-stock-${productId}-modal`);
                    if (modalStockSpan) {
                        modalStockSpan.textContent = `库存: ${product.stock}`;
                    }
                }
            } catch (error) {
                console.error('刷新库存失败:', error);
            }
        }
    </script>
</body>

</html>